package com.sds.sweng.swat.miplatform.ui.design.policies;

import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.FlowLayoutEditPolicy;
import org.eclipse.gef.requests.ChangeBoundsRequest;
import org.eclipse.gef.requests.CreateRequest;

import com.sds.sweng.swat.miplatform.ui.design.models.MiplatformComponent;
import com.sds.sweng.swat.miplatform.ui.design.models.MiplatformContainer;
import com.sds.sweng.swat.miplatform.ui.design.models.commands.ReorderPartCommand;
import com.sds.sweng.swat.miplatform.ui.design.parts.area.sub.TableSubAreaPart;

public class TableFlowLayoutEditPolicy extends FlowLayoutEditPolicy {

	protected Command getCreateCommand(CreateRequest request) {
		return null;
	}

	@Override
	protected Command createAddCommand(EditPart child, EditPart after) {
		return null;
	}

	protected Command createMoveChildCommand(EditPart child, EditPart after) {
		if (!(child instanceof TableSubAreaPart))
			return null;

		int oldIndex = getHost().getChildren().indexOf(child);
		int newIndex = -1;

		if (after != null && after instanceof TableSubAreaPart) {
			newIndex = getHost().getChildren().indexOf(after);

			if (oldIndex < newIndex) {
				newIndex -= 1;
			}

			if (oldIndex == newIndex) {
				return null;
			}
		} else if (after == null) {
			return null;
		} else {
			int afterIndex = getHost().getChildren().indexOf(after);

			if (afterIndex == 0)
				return null;

			if (getHost().getChildren().get(afterIndex-1) instanceof TableSubAreaPart)
				newIndex = getHost().getChildren().indexOf(after);

			if (oldIndex < newIndex) {
				newIndex -= 1;
			}

			if (oldIndex == newIndex) {
				return null;
			}
		}


		ReorderPartCommand command = new ReorderPartCommand(
				(MiplatformContainer) getHost().getModel(),
				(MiplatformComponent) child.getModel(),
				newIndex);

		return command;
	}

	protected void showLayoutTargetFeedback(Request request) {
		if (request instanceof ChangeBoundsRequest) {
			List editParts = ((ChangeBoundsRequest) request).getEditParts();

			if (editParts.size() == 0) {
				return;
			}
		}

		super.showLayoutTargetFeedback(request);
	}

}
